package com.yaoyong.yy_demo.config;

import com.yaoyong.yy_demo.module.security.CustomUserService;
import com.yaoyong.yy_demo.module.security.MyPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

import javax.sql.DataSource;

/**
 * 用户认证配置
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    //    @Bean
    UserDetailsService customUserService() {
        return new CustomUserService();
    }

    /**
     * 自定义认证方式
     *
     * @param auth
     * @throws Exception
     */
//    @Override
    protected void configure2(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService());
    }


    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private DataSource dataSource;


    /**
     * JDBC中的用户
     *
     * @param auth
     * @throws Exception
     */
//    @Override
    protected void configure1(AuthenticationManagerBuilder auth) throws Exception {
        //1.默认的用户角色权限查询语句
        //auth.jdbcAuthentication().dataSource(dataSource);
        //自定义用户和权限语句
        auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username,password,true from myusers where username=?")
                .authoritiesByUsernameQuery("select username ,role from roles where username=?");
    }

    /**
     * 内存中的用户
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //密码以明文方式匹配
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                .withUser("yao").password("yao").roles("USER")
                .and()
                .withUser("wisely").password("wisely").roles("USER");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //不能拦截/resources/static/**下的静态资源
        web.ignoring().antMatchers("/**/*.js", "/**/*.css", "/**/*.jpg", "/**/*.ico")
                .antMatchers("/assets/**", "/bootstrap/**", "/images/**", "/druid/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                /**
                 * 对"/"和"/login"不拦截   1.antMatchers():使用ant风格的路径匹 2.regexMatchers():使用正匹配 3.anyRequest():匹配所有
                 *
                 * access():EL表达式结果为true可访问
                 * anonymous():匿名可访问
                 * denyAll():用户不能访问
                 * fullyAuthenticated():用户完全认证可以访问(非rememberMe可自动登录)
                 * rememberMe():允许通过rememberMe登录的用户访问,开启cookie存储用户信息
                 * authenticated():用户登录后可访问
                 * permitAll():用户可任意访问
                 *
                 * */
                .antMatchers("/", "/login", "/error").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/chat")
                .failureUrl("/login?error")
                .permitAll()
                .and()
                .rememberMe()
                .tokenValiditySeconds(60 * 60 * 24 * 7)
                //cookie中的私钥
                .key("mykey")
                .and()
                .logout()
                .logoutUrl("/custom-logout")
                .logoutSuccessUrl("/logout-success")
                .permitAll();
    }
}


